﻿#region

using System;
using System.Windows;
using System.Windows.Browser;

#endregion

namespace Radovici.Ctrls
{
    public class VideoBlock : HtmlBlock
    {
        #region Private fields

        private readonly string _guid;
        private HtmlElement _video;

        #endregion

        public static readonly DependencyProperty VideoUrlProperty =
            DependencyProperty.Register("VideoUrl", typeof (string), typeof (VideoBlock),
                                        new PropertyMetadata(string.Empty, onVideoUrlChanged));

        public VideoBlock()
        {
            Overflow = false;
            _guid = Guid.NewGuid().ToString();
            LayoutUpdated += onLayoutUpdated;
        }

        public string VideoId
        {
            get { return _guid; }
        }

        protected virtual string VideoHtml
        {
            get { return HtmlHelper.GetVideoHtml(VideoUrl, _guid); }
        }

        public string VideoUrl
        {
            get { return (string) GetValue(VideoUrlProperty); }
            set { SetValue(VideoUrlProperty, value); }
        }

        private void onLayoutUpdated(object sender, EventArgs e)
        {
            refreshSize();
        }

        private static void onVideoUrlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            //if (e.NewValue != null)
            //{
            var block = d as VideoBlock;
            if (block != null)
            {
                block.Html = block.VideoHtml;
            }
            //}
        }

        private void refreshSize()
        {
            if (_video == null)
            {
                HtmlDocument doc = HtmlPage.Document;
                _video = doc.GetElementById(_guid);
                if (_video != null)
                {
                    _video.AttachHtmlElement();
                }
            }
        }
    }
}